<template>
  <!--  质检记录-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline" label-width="auto">
        <el-row>
          <el-col :span="6">
            <el-form-item label="质检类型" required>
              <el-select v-model="searchParam.qualityType" placeholder="请选择质检类型" clearable style="width: 250px">
                <el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品" required>
              <el-select v-model="searchParam.materalIdValue" remote :remote-method="remoteMethod" filterable
                         style="width: 250px"
                         placeholder="请选择产品"
                         @change="handleTeamChange">
                <el-option v-for="(item, index) of materialList" :key="index" :label="item.productName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工序" required>
              <el-select v-model="searchParam.procedureName" clearable
                         placeholder="请选择工序" filterable style="width: 250px" @change="handleProcedureChange"
              >
                <el-option v-for="item in processData" :key="item.procedureName" :label="item.procedureName" :value="item.procedureName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期范围" prop="date">
              <el-date-picker
                  v-model="searchParam.dateList"
                  style="width: 100%"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                   style="margin-left: 10px;">导出
        </el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" border height="calc(100vh - 325px)">
        <!-- 固定列 -->
        <el-table-column type="index" fixed="left" width="60" align="center"/>
        <el-table-column prop="testitemName" align="center" label="质检项名称" fixed="left" min-width="180"/>
        <el-table-column prop="upperValue" align="center" label="上公差" min-width="120"/>
        <el-table-column prop="otherDefect" align="center" label="默认值" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="lowerValue" align="center" label="下公差" min-width="120"/>

        <!-- 动态多级表头 -->
        <template v-for="batch in allBatches" :key="batch">
          <el-table-column :label="`${batch.createTime} ( ${batch.no} )`" align="center">
            <el-table-column
                v-for="workpiece in batch.workpieces"
                :key="`${batch.no}_${workpiece}`"
                :label="workpiece"
                min-width="150"
                align="center">
              <template #default="{ row }">
                {{ getRealityValue(row, batch.no, workpiece) || '--' }}
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </el-table>
    </div>
  </div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import {Refresh, Search} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {reactive, ref} from 'vue';
import axios from 'axios';
import moment from 'moment';

const searchFormRef = ref<FormInstance>(); // 添加表单引用

onMounted(() => {
  getQualityPlanList();
  // searchParam.value = {
  //   "qualityType": "1",
  //   "materalIdValue": "230e6963d641b88175b4ec48e25b7479",
  //   "procedureName": "PD3-冲压落料",
  //   "procedureId": "1e3d01ae9966ff00f53e62e1e9d64c98",
  //   "outMaterialId": "682cc5da3b0260839a2edcaf7b07830d",
  //   "dateList": [
  //     "2025-04-01",
  //     "2025-04-02"
  //   ],
  //   "startDateTime": "2025-04-01 00:00:00",
  //   "endDateTime": "2025-04-02 23:59:59",
  //   "current": 1,
  //   "pageSize": 10
  // }
  // handleSearch()
});

// 计算所有批次数据
const allBatches = computed(() => {
  const batchMap = new Map()

  // 遍历所有数据收集批次信息
  paginatedData.value?.forEach(row => {
    row.info?.forEach(infoItem => {
      const key = infoItem.no
      if (!batchMap.has(key)) {
        batchMap.set(key, {
          no: infoItem.no,
          createTime: infoItem.createTime,
          workpieces: new Set()
        })
      }
      // 收集该批次下的所有工件号
      infoItem.realityNumberList?.forEach(work => {
        batchMap.get(key).workpieces.add(work.workpieceNumber)
      })
    })
  })

  // 转换数据结构
  return Array.from(batchMap.values()).map(batch => ({
    ...batch,
    workpieces: Array.from(batch.workpieces)
  }))
})

// 数据获取方法
const getRealityValue = (row, batchNo, workpieceNo) => {
  // 安全访问数据
  const targetBatch = row.info?.find(i => i.no === batchNo)
  const targetWork = targetBatch?.realityNumberList?.find(
      w => w.workpieceNumber === workpieceNo
  )
  return targetWork?.realityValueList?.[0]
}

// 日期格式化
const formatDate = (datetime) => {
  return datetime?.split(' ')[0] || '未知日期'
}


const qualityPlanList = ref({});

const getQualityPlanList = () => {
  // axiosInstance.post('/api/basedataQualityScheme/getAll', {})
  // 	.then(res => {
  // 		if (res.code !== 200) {
  // 			ElMessage.error(res.message);
  // 			return false;
  // 		}
  // 		qualityPlanList.value = res.data;
  // 	});

  axiosInstance.post('/api/basedataProduct/getPage', {
    current: 1, pageSize: 50
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data.records;
      });
};


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const schemeTaskForm = ref({});


const configTableShow = ref(false);


const handleClick = (e) => {
  console.log(e, 'handleClick');
};
// 配置质检项表
const configTable = ref([]);

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});
// 点击配置质检项表
const handleConfigEdit = (e) => {
  const row = JSON.parse(JSON.stringify(e));
  console.log(row);
  rowInfo.value = row;
  const list = JSON.parse(row.qualityJson);
  // schemeTaskForm.value = list.schemeTaskForm ? list.schemeTaskForm : [];
  schemeTaskForm.value = row.schemeTaskForm ? row.schemeTaskForm : [];
  configTable.value = list.configTable;
  console.log(configTable, 'configTable');
  const param = JSON.parse(row.qualityJson);
  const loop = {...param, ...row};
  Object.assign(formData, loop);
  isEdit.value = true;
  configTableShow.value = true;
};

const materialList = ref({});

const materialData = ref({});
const showMaterial = ref(false);
// 质检列表
const isConfigEdit = ref(false);

const isConfigIndex = ref(null);


const getQualityPlan = (e) => {
  let name = '';
  qualityPlanList.value.forEach(item => {
    if (item.id == e) {
      name = item.name;
    }
  });
  return name;
};

const getQualityWay = (e) => {
  let name = '';
  qualityWayList.value.forEach(item => {
    if (item.value == e) {
      name = item.label;
    }
  });
  return name;
};

const getQualityTypeList = (e) => {
  let name = '';
  qualityTypeList.value.forEach(item => {
    if (item.value == e) {
      name = item.label;
    }
  });
  return name;
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    // showConfig.value = false;
    // showMaterial.value = false
    configTableShow.value = false;
    // 刷新配置质检项列表
    // handleConfigEdit(rowInfo.value);
    handleSearch();
  });
};


const materialId = ref(null);

const remoteMethod = (value) => {
  console.log(value);

  if (!value) {
    return;
  }
  axiosInstance.post('/api/basedataProduct/getPage', {
    current: 1, pageSize: 50, productName: value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data.records;
      });
};
const processData = ref([]); // 工序
const handleTeamChange = (value) => {
  // searchParam.value.procedureIds = [];
  axiosInstance.get('/api/basedataProcedure/queryByMateralIdProcedure', {
    params: {materalId: value}
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }

        const procedureMap = new Map();

        res.data.forEach(item => {
          if (!procedureMap.has(item.procedureName)) {
            procedureMap.set(item.procedureName, {
              ...item,
              outMaterialIds: item.outMaterialId ? [item.outMaterialId] : []
            });
          } else {
            const existing = procedureMap.get(item.procedureName);
            if (item.outMaterialId && !existing.outMaterialIds.includes(item.outMaterialId)) {
              existing.outMaterialIds.push(item.outMaterialId);
            }
          }
        });
        processData.value = Array.from(procedureMap.values());
        console.log(processData.value, 123)
        searchParam.value.procedureName = null
        // setList();
      });
};
const handleProcedureChange = (value) => {
  if (value) {
    searchParam.value.outMaterialIds = processData.value.find(item => item.procedureName == value).outMaterialIds
  } else {
    searchParam.value.outMaterialIds = null
    searchParam.value.procedureName = null
  }
}
const uniqueProcedureNames = ref([]);
const setList = () => {
  const list = JSON.parse(JSON.stringify(processData.value));
  const loop = list.reduce((unique, item) => {
    if (!unique.includes(item.procedureName)) {
      unique.push(item.procedureName);
    }
    return unique;
  }, []);
  uniqueProcedureNames.value = loop;
  console.log(loop, 'uniqueProcedureNamesuniqueProcedureNames');
};

const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const qualityWayList = ref([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
]);


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList.value) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = ref([
  {
    label: '首件检',
    value: '1',
    type: 'material'
  },
  {
    label: '末件检',
    value: '2',
    type: 'material'
  },
  {
    label: '生产',
    value: '3',
    type: 'material'
  },
  {
    label: '巡检',
    value: '4',
    type: 'material'
  },
  {
    label: '入库检',
    value: '5',
    type: 'procedure'
  },
  {
    label: '出库检',
    value: '6',
    type: 'procedure'
  },
  {
    label: '来料检',
    value: '7',
    type: 'procedure'
  }
  // 继续添加更多检查类型...
]);

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
  qualityJson: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: '',
  qualityJson: null
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  sourceNo: [
    {required: true, message: '请输入来源单号', trigger: 'blur'}
  ],
  qualityPlan: [
    {required: true, message: '请选择质检方案', trigger: 'blur'}
  ],
  samplingMethod: [
    {required: true, message: '请选择质检方式', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref()
const headerInfo = ref([])

const downLoading = ref(false);
const handleExport = () => {
  if (!searchParam.value.qualityType) {
    ElMessage.error('请选择质检类型');
    return false
  }
  // if (!searchParam.value.materalId) {
  //   ElMessage.error('请选择产品');
  //   return false
  // }
  if (!searchParam.value.procedureName) {
    ElMessage.error('请选择工序');
    return false
  }
  const param = {...searchParam.value}
  if (param.dateList) {
    param.startDateTime = param.dateList[0] + ' 00:00:00';
    param.endDateTime = param.dateList[1] + ' 23:59:59';
  } else {
    ElMessage.error('请选择日期');
    return false;
  }
  downLoading.value = true;
  axios.post('/api/qualitySchemeTask/getReportExcel', {
    ...param
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '质检报告查询' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


// 获取列表接口
const handleSearch = () => {
      if (!searchParam.value.qualityType) {
        ElMessage.error('请选择质检类型');
        return false
      }
      // if (!searchParam.value.materalId) {
      //   ElMessage.error('请选择产品');
      //   return false
      // }
      if (!searchParam.value.procedureName) {
        ElMessage.error('请选择工序');
        return false
      }
      const param = {...searchParam.value}
      if (param.dateList) {
        param.startDateTime = param.dateList[0] + ' 00:00:00';
        param.endDateTime = param.dateList[1] + ' 23:59:59';
      } else {
        ElMessage.error('请选择日期');
        return false;
      }
      paginatedData.value = []
      axiosInstance.post('/api/qualitySchemeTask/getReportPage', {
        ...param,
        ...{
          current: 1,
          pageSize: 10
        }
      })
          .then(res => {
                if (res.code !== 200) {
                  ElMessage.error(res.message);
                  return false;
                }
                if (res.data.records.length > 0) {
                  // const loop = res.data.records;
                  // const list = [];
                  // for (const item of loop) {
                  //   let param = JSON.parse(item.qualityJson).configTable;
                  //   param.map(items => {
                  //     items.no = item.no;
                  //     items.time = item.createTime;
                  //   });
                  //   list.push(...param);
                  // }
                  // // paginatedData.value = list;
                  // console.log(list);
                  //
                  // const mergedList = list.reduce((acc, current) => {
                  //   const existingItem = acc.find(item => item.testitemName === current.testitemName);
                  //   if (existingItem) {
                  //     existingItem.info.push({
                  //       workpieceNumber: current.workpieceNumber,
                  //       realityNumber: current.realityNumber,
                  //       testitemName: current.testitemName
                  //     });
                  //   } else {
                  //     const newItem = {
                  //       lowerBias: current.lowerBias,
                  //       upperBias: current.upperBias,
                  //       defaultValue: current.defaultValue,
                  //       testitemName: current.testitemName,
                  //       no: current.no,
                  //       createTime: current.createTime,
                  //       info: [{
                  //         workpieceNumber: current.workpieceNumber,
                  //         realityNumber: current.realityNumber,
                  //         testitemName: current.testitemName
                  //       }]
                  //     };
                  //     acc.push(newItem);
                  //   }
                  //
                  //   return acc;
                  // }, []);
                  //
                  // console.log(mergedList);

                }
                paginatedData.value = res.data.records;
                pageTotal.value = res.data.total;
                if (res.data.records && res.data.records.length > 0) {
                  headerInfo.value = res.data.records[0].info
                }
              }
          )
      ;
    }
;

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  handleSearch();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  handleSearch();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  paginatedData.value = []
  pageTotal.value = 0
  // current.value = 1
  // handleSearch();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  const param = JSON.parse(row.qualityJson);
  const list = {...param, ...row};
  Object.assign(formData, list);
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/qualitySchemeTask/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      handleSearch(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      const jsonString = JSON.stringify(formData);
      formData.qualityJson = jsonString;
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/qualitySchemeTask/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      } else {
        // 新建
        const paramData = formData;
        paramData.id = null;
        paramData.status = false;
        axiosInstance.post('/api/qualitySchemeTask/save', paramData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          handleSearch(); // 刷新数据
        });
      }

    }
  });
};
</script>
<style scoped>
.content {
  /*padding: 20px;*/
}
</style>
